package DAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import POJO.Editora;

public class EditoraDao 
{
	Connection c;
	
	public EditoraDao()
	{
		GenericDao gDao = new GenericDao();
		c = gDao.getConnection();
	}
	
	public void CadastrarEditora(Editora e) throws SQLException
	{
		String sql = "INSERT INTO Editora (nomeEditora) VALUES (?)";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setString(1, e.getNomeEditora());
		ps.execute();
		ps.close();
	}
	
	public void AlterarEditora(Editora e) throws SQLException
	{
		String sql = "UPDATE Editora SET nomeEditora = ? WHERE codEditora = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setString(1, e.getNomeEditora());
		ps.setInt(2, e.getCodEditora());
		ps.execute();
		ps.close();
	}
	
	public void RemoveEditora(Editora e) throws SQLException
	{
		String sql = "DELETE Editora WHERE codEditora = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setInt(1, e.getCodEditora());
		ps.execute();
		ps.close();
	}
	
	public int ProximoCodigo() throws SQLException
	{
		int codigo = 1;
		String sql = "SELECT MAX(codEditora + 1) AS codEditora FROM Editora";
		PreparedStatement ps = c.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		if(rs.next())
		{
			codigo = rs.getInt("codEditora");
		}
		rs.close();
		ps.close();
		return codigo;
	}
	
	public Editora consultaEditora(Editora e) throws SQLException
	{
		
		String sql = "SELECT codEditora, nomeEditora FROM Editora WHERE codEditora = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setInt(1, e.getCodEditora());
		ResultSet rs = ps.executeQuery();
		if(rs.next())
		{
			e.setCodEditora(rs.getInt("codEditora"));
			e.setNomeEditora(rs.getString("nomeEditora"));
		}
		rs.close();
		ps.close();
		return e;
	}
	
	public List<Editora> listaEditora() throws SQLException
	{
		List<Editora> listaEditora = new ArrayList<Editora>();
		String sql = "SELECT * FROM Editora ORDER BY nomeEditora";
		PreparedStatement ps = c.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		while(rs.next())
		{
			Editora e = new Editora();
			e.setCodEditora(rs.getInt("codEditora"));
			e.setNomeEditora(rs.getString("nomeEditora"));
			listaEditora.add(e);
		}
		rs.close();
		ps.close();
		return listaEditora;
	}
}
